package com.woniu.tms.manage.service.impl;

import com.woniu.tms.entity.RolePermission;
import com.woniu.tms.entity.RolePermissionExample;
import com.woniu.tms.manage.service.RolePermissionService;
import com.woniu.tms.mapper.RoleMapper;
import com.woniu.tms.mapper.RolePermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class RolePermissionServiceImpl implements RolePermissionService {

    @Autowired
    RolePermissionMapper rolePermissionMapper;

    @Override
    public void assign(Integer rid, String pids) {
        RolePermissionExample example = new RolePermissionExample();
        RolePermissionExample.Criteria criteria = example.createCriteria();
        criteria.andRidEqualTo(rid);
        rolePermissionMapper.deleteByExample(example);
        String[] split = pids.substring(0, pids.length() - 1).split(",");
        for (String pid : split) {
            if (!"".equals(pid) && pid != null) {
                RolePermission rolePermission = new RolePermission();
                rolePermission.setRid(rid);
                rolePermission.setPid(Integer.parseInt(pid));
                rolePermissionMapper.insertSelective(rolePermission);
            }
        }
    }

    @Override
    public List<RolePermission> getByRid(Integer rid) {
        RolePermissionExample example = new RolePermissionExample();
        RolePermissionExample.Criteria criteria = example.createCriteria();
        criteria.andRidEqualTo(rid);
        return rolePermissionMapper.selectByExample(example);
    }

    @Override
    public void add(Integer rid, Integer pid) {
        RolePermission rolePermission = new RolePermission();
        rolePermission.setPid(pid);
        rolePermission.setRid(rid);
        rolePermissionMapper.insertSelective(rolePermission);
    }

    @Override
    public void remove(Integer rid, Integer pid) {
        RolePermissionExample example = new RolePermissionExample();
        RolePermissionExample.Criteria criteria = example.createCriteria();
        criteria.andRidEqualTo(rid);
        criteria.andPidEqualTo(pid);
        rolePermissionMapper.deleteByExample(example);
    }

}
